﻿using System.Diagnostics;
using System.Drawing;
using System.IO;

public class DotToImageConverter
{
    private const string ExtImg = "png";

    public static byte[] CreateByteArrayFrom(string dotSource)
    {
        var process = StartDotProcess();
        var standardInput = process.StandardInput;

        standardInput.Write(dotSource);
        standardInput.Close();

        var byteArray = GetByteArray(process.StandardOutput.BaseStream);
        process.WaitForExit();

        return byteArray;
    }

    public static Image CreateImageFrom(string dotSource)
    {
        var process = StartDotProcess();
        var standardInput = process.StandardInput;

        standardInput.Write(dotSource);
        standardInput.Close();

        var image = Image.FromStream(process.StandardOutput.BaseStream);
        process.WaitForExit();

        return image;
    }

    private static byte[] GetByteArray(Stream imageStream)
    {
        using (var memoryStream = new MemoryStream())
        {
            var buffer = new byte[32768];

            while (true)
            {
                var count = imageStream.Read(buffer, 0, buffer.Length);

                if (count >= 1)
                    memoryStream.Write(buffer, 0, count);
                else
                    break;
            }

            return memoryStream.ToArray();
        }
    }

    private static Process StartDotProcess()
    {
        var arguments = string.Format("-T{0}", "png");

        var startInfo = new ProcessStartInfo("dot.exe", arguments)
        {
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardInput = true,
            RedirectStandardOutput = true
        };

        return Process.Start(startInfo);
    }
}

